using System.Collections;
using System.Linq;
using Castle.ActiveRecord;
using Karma.Framework.Core.Domain;
using Karma.Framework.Core.Repository;
using NHibernate;

namespace Karma.Framework.Core.Modules.System.QueryEditor
{
    public class QueryEditorService : IQueryEditorService
    {
        public QueryEditorService(IRepository<DomainObject> repo)
        {
            Repository = repo;
        }

        private IRepository<DomainObject> Repository { get; set; }

        public QueryResult ExecuteQuery(QuerySpecification specification)
        {
            if(string.IsNullOrEmpty(specification.QueryLang) || specification.QueryLang.Equals("HQL"))
            {
                return new QueryResult
                {
                    Count = 0,
                    Data = ((IList)ActiveRecordMediator.Execute(typeof(DomainObject),
                       delegate(ISession session, object instance)
                       {
                           var query = session.CreateQuery(specification.Query);
                           query.SetReadOnly(true);
                           query.SetFlushMode(FlushMode.Never);
                           return query.List();
                       }, null)).Cast<object>().ToArray()
                };
            }

            return new QueryResult
            {
                Count = 0,
                Data = ((IList)ActiveRecordMediator.Execute(typeof(DomainObject),
                   delegate(ISession session, object instance)
                   {
                       var query = session.CreateSQLQuery(specification.Query);
                       return query.List();
                   }, null)).Cast<object>().ToArray()
            };
        }
    }
}